import React,{useState,useEffect} from 'react'
import HOCLogin from '../../utils/HOCLogin'
import axios from 'axios'

function Shopcar(props) {
  const [list,setlist]=useState([])
  const [allcheck,setallcheck]=useState(false)
  let [totalprice,settotalprice]=useState(0)
  let [totalnum,settotalnum]=useState(0)
  useEffect(()=>{
    axios.get('/shoplist').then(res=>{
      setlist(res.data)
    })
  },[])
  const onallcheck=(e)=>{
    setallcheck(e.target.checked)
    list.forEach(item=>{
      item.flag=e.target.checked
    })
    setlist([...list])
    total()
  }
  const danxuan=(id)=>{
    list.forEach(item=>{
      if(item.id===id){
        item.flag=!item.flag
      }
    })
    let all=list.every(item=>item.flag)
    setallcheck(all)
    setlist([...list])
    total()
  }
  const jia=(id)=>{
    list.forEach(item=>{
      if(item.id===id){
        item.num++
      }
    })
    setlist([...list])
    total()
  }
  const jian=(id)=>{
     list.forEach(item=>{
      if(item.id===id){
        item.num--
      }
    })
    setlist([...list])
    total()
  }
  const total=()=>{
    totalnum=list.reduce((sum,item)=>{
      if(item.flag){
        sum+=item.num
      }
      return sum
    },0)
    settotalnum(totalnum)
    totalprice=list.reduce((sum,item)=>{
      if(item.flag){
        sum+=(item.num*item.price)
      }
      return sum
    },0)
    settotalprice(totalprice.toFixed(2))
  }
  return (
    <div className='shopcar'>
      <div className='title'>
        <input type="checkbox" name="" id=""  
          checked={allcheck} 
          onChange={onallcheck}
        />全选
      </div>
      <div className='list'>
        {list.length?list.map((item)=>{
          console.log(list);
          return <li key={item.id}>
            <input type="checkbox" name="" id="" 
            checked={item.flag}
            onChange={()=>{danxuan(item.id)}}
            />
            <img src={item.img} alt="" />
            <div className='right'>
              <p>{item.title}</p>
              <p>{item.price}</p>
              <p>
                <button onClick={()=>{jian(item.id)}} disabled={item.num<=1}>-</button>
                {item.num}
                <button onClick={()=>{jia(item.id)}}>+</button>
              </p>
            </div>
          </li>
        }):'暂无数据'}
      </div>
      <div className='footer'>
        <input type="checkbox" name="" id="" 
        checked={allcheck}
        onChange={onallcheck}
        />
        <p>总量：{totalnum}</p>
        <p>总计：{totalprice}</p>
        <button disabled={totalnum===0}>结算</button>
      </div>
    </div>
  )
}

export default HOCLogin(Shopcar)
